#!/bin/bash

SCRIPT_PATH="/opt/middleware/AtlasEdge/software/edge_site/edge_manager/src/script"
WORK_PATH="/opt/middleware/AtlasEdge"

. ${SCRIPT_PATH}/common.sh
. ${SCRIPT_PATH}/log_util.sh

ATLASEDGE_SERVICE_FILE="atlasedge.service"
ATLASEDGE_MAIN_BIN="${WORK_PATH}/edge_main.sh"
ATLASEDGE_CONFIG_FILE="${WORK_PATH}/config/config.ini"

function usage() {
    echo "stop -- stop software"
    echo "parameters:"
    echo "usage: "
    echo "     stop"
}

precheck_env() {
    return 0
}

function kill_orphan_process()
{
    local app_list="edge_main.sh|mod_backup.sh|ha_status_monitor.sh|mdw_log_retate_by_size.sh|edge_core|AscendK8sDevicePlugin|postern_main.py"
    local pids="$(ps -ww -eo pid,cmd | grep -v grep | grep AtlasEdge | grep -E $app_list | awk '{print $1}')"
    for pid in ${pids[@]}; do
        logger_Info "kill orphan process $pid"
        kill -9 $pid
    done
}

stop_edge()
{
    NO_SYS_LOAD_MODE=`ReadINIfile ${ATLASEDGE_CONFIG_FILE} SYS no_sys_load_mode`
    if [ "${NO_SYS_LOAD_MODE}" == "1" ]; then
        logger_Info "atlasEdge is no_sys_load_mode stop process"
        for ps in `ps -ww -eo pid,cmd | grep -v grep | grep -w $ATLASEDGE_MAIN_BIN | awk '{print $1}'`
        do
            logger_Info "kill process $ps"
            kill -9 -$ps
            kill -- -$ps
        done
        return 0
    fi

    # check service is enable
    local IsEnable="`sudo systemctl is-enabled ${ATLASEDGE_SERVICE_FILE} 2>/dev/null`"
    if [ "${IsEnable}" != "enabled" ]; then
        logger_Info "atlasEdge is stoped already"
        return 0
    fi

    # check is own runing program by ExecStart args
    local IsOwnerProgram="`sudo systemctl show -p ExecStart ${ATLASEDGE_SERVICE_FILE} --no-pager`"
    IsOwnerProgram=`echo ${IsOwnerProgram} | grep  -w ${ATLASEDGE_MAIN_BIN} | wc -l`
    if [ "${IsOwnerProgram}" -eq 0 ]; then
        logger_Info "atlasEdge  runing program is not owner ret"
        return 0
    fi

    if [ "$1" == "stopapp" ];then
        stop_application ${ATLASEDGE_SERVICE_FILE}
    else
        stop_service ${ATLASEDGE_SERVICE_FILE}
    fi
    if [ $? -ne 0 ]; then
        logger_Error "stop atlasedge main failed arg:$1"
        return 1
    fi

    kill_orphan_process

    logger_Info "atlasEdge is stopped."
    return 0
}

main()
{
    if [ "$#" -gt 0 ]; then
        if [ "$1" == "-h" ]; then
            usage
            return 0
        fi
    fi

    precheck_env

    stop_edge "$@"
}

main "$@"
RESULT=$?
exit $RESULT